package com.leyantech.ecp.agenx.session.manager.loader;

import com.leyantech.ecp.agenx.common.redis.RedissonOperation;
import com.leyantech.ecp.agenx.session.client.Assistant;

import com.google.common.cache.CacheLoader;
import com.google.common.collect.Sets;
import com.google.inject.Singleton;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-22.
 */
@Slf4j
@Singleton
public class OnlineAssistantCacheLoader extends CacheLoader<String, Set<Assistant>> {

  @Override
  public Set<Assistant> load(@NonNull String storeId) {

    return RedissonOperation.STORE_ASSISTANT
        .executor(storeId)
        .get(RMap::readAllValues, "readAllValues")
        .stream()
        .map(onlineAssistantSession ->
            Assistant.builder()
                .storeId(storeId)
                .assistantId(onlineAssistantSession.getAssistantId())
                .clientUuid(onlineAssistantSession.getClientUuid())
                .clientVersion(onlineAssistantSession.getClientVersion())
                .timestamp(onlineAssistantSession.getTimestamp())
                .serviceMode(onlineAssistantSession.getServiceMode())
                .functionList(onlineAssistantSession.getFunctions())
                .action(onlineAssistantSession.getAction())
                .build()
        )
        .collect(Collectors.toCollection(Sets::newConcurrentHashSet));
  }

}
